package com.interview.a_多线程.h_多线程问题.c_死锁.a_必然死锁;

/**
 * 必然死锁
 */
public class KillLock {
    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + " 拿到锁1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 拿着锁1， 开始抢锁2");
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + " 拿到锁2");
                }
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + " 拿到锁2");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 拿着锁2， 开始抢锁1");
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + " 拿到锁1");
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.setName("thread1");
        thread1.start();

        Thread2 thread2 = new Thread2();
        thread2.setName("thread2");
        thread2.start();

    }
}
